package luafrontend.values;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import luafrontend.exceptions.ConversionException;

public class LuaReturnValue extends LuaValue implements Iterable<LuaValue> {
	private final List<LuaValue> vals = new ArrayList<LuaValue>(3);
	
	public void add(LuaValue value) {
		vals.add(value);
	}
	
	public LuaValue narrow() {
		if (vals.isEmpty()) {
			return new LuaNil();
		}
		else {
			return vals.get(0);
		}
	}
	
	public LuaNumber asNumber() throws ConversionException {
		return narrow().asNumber();
	}
	
	public LuaString asString() throws ConversionException {
		return narrow().asString();
	}
	
	public LuaFunction asFunction() throws ConversionException {
		return narrow().asFunction();
	}
	
	public LuaTable asTable() throws ConversionException {
		return narrow().asTable();
	}
	
	public LuaBool asBool() throws ConversionException {
		return narrow().asBool();
	}
	
	public boolean isNil() {
		return narrow().isNil();
	}

	@Override
	public String toString() {
		if (vals.isEmpty()) {
			return "retval nil";
		}
		else {
			StringBuffer buffer = new StringBuffer("retval ");
			buffer.append(vals.get(0).toString());
			for (int i = 1; i < vals.size(); ++i) {
				buffer.append(", ");
				buffer.append(vals.get(i).toString());
			}
			
			return buffer.toString();
		}
	}

	@Override
	public Iterator<LuaValue> iterator() {
		return vals.iterator();
	}
}
